<script setup lang="ts" name="CreateGroupModal">
import { ref, watch, computed } from 'vue';
import { useContactStore } from '@/stores/contacts';
import Avatar from '@/components/Avatar/index.vue';
import { useGlobalStore } from '@/stores/global';
import { Search } from '@element-plus/icons-vue';
import apis from '@/services/apis';
import type { renderContent } from 'element-plus/es/components/transfer';
import { useUserInfo } from '@/hooks/useCached';
import { ElMessage } from 'element-plus';

const globalStore = useGlobalStore();
const contactStore = useContactStore();
const data = ref<Array<{
  label: string;
  key: string;
  initial: string;
  disabled: boolean;
}>>([]);

const contactsList = computed(() => contactStore.contactsList);
const selectedUid = computed(() => globalStore.createGroupModalInfo.selectedUid);

watch(selectedUid, (val) => {
    val.forEach((item) => {
    const dataItem = data.value.find((i) => i.key === item);
      if (dataItem) {
      dataItem.disabled = true;
      }
  });
}, { immediate: true });

const isModalVisible = ref<boolean>(false); // 控制窗口显示隐藏的状态变量

// 监听 isModalVisible 的变化，窗口关闭时清除数据
watch(isModalVisible, (newValue) => {
  if (!newValue) {
    data.value = [];
    selected.value = [];
    searchText.value = '';
    lastSearchResult.value = null;
  }
});

const selected = ref<string[]>([]); // 确保 selected 是字符串数组

const emit = defineEmits(['checked']);

const renderFunc: renderContent = (h, option) => {
  const user = useUserInfo(option.key);
  return h('div', { style: 'display:flex;align-items:center;gap:6px' }, [
    h(Avatar, { src: user.value.avatar, size: 20, class: 'avatar' }),
    h('div', { class: 'tem-info-name' }, user.value.userName),
  ]);
};

const handleChange = () => {
  emit('checked', selected.value);
};

const searchText = ref<string>(''); // 确保 searchText 是字符串
const lastSearchResult = ref<{ key: string } | null>(null); // 用于存储上一次的搜索结果


const handleSearch = async () => {
  if (searchText.value.trim() === '') {
    return;
  }
  const userInfo = await apis.getUserInfoByPhone({ phone: searchText.value }).send();

  if (!userInfo) {
    ElMessage.error('该用户不存在');
    return;
  }

  const existingItem = data.value.find(item => item.key === userInfo.userId);
  if (existingItem) {
    ElMessage.warning('已选择该用户');
    return;
  }

  const newSearchResult = {
    label: userInfo.userId,
    key: userInfo.userId,
    initial: userInfo.userId,
    disabled: false,
  };
  data.value = [newSearchResult, ...data.value];
  lastSearchResult.value = newSearchResult;
};

// 监听 searchText 的变化，清空搜索结果
watch(searchText, (newVal) => {
  if (newVal === '') {
    if (lastSearchResult.value && !selected.value.includes(lastSearchResult.value.key)) {
      let a = lastSearchResult.value.key;
      data.value = data.value.filter(item => item.key !== a);
      lastSearchResult.value = null;
    }
  }
});
</script>

<template>
  <div>
    <el-input
      placeholder="请输入手机号"
      v-model="searchText"
      class="input-with-select"
      @keyup.enter="handleSearch"
    >
      <template #append>
        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
      </template>
    </el-input>
  <el-transfer
    v-model="selected"
    style="display: inline-block; text-align: left"
    :render-content="renderFunc"
      :titles="['选项', '已选择']"
    :format="{
      noChecked: '${total}',
      hasChecked: '${checked}/${total}',
    }"
    :data="data"
    @change="handleChange"
    ></el-transfer>
  </div>
</template>

<style lang="scss" src="./styles.scss" scoped />